package banner

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateBannerLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateBannerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateBannerLogic {
	return &UpdateBannerLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateBannerLogic) UpdateBanner(in *backend.BannerInfo) (*backend.BaseResp, error) {
	// logx.Infof("UpdateBanner : %+v ", in)

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(in.Ids) > 0 { // 批量修改状态
		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				banner, err := l.svcCtx.Banner.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				if in.Status != nil {
					banner.Status = uint8(*in.Status)
				}
				banner.UpdatedAt = now
				err = l.svcCtx.Banner.Update(l.ctx, tx, banner, nil)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &backend.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	id := *in.Id
	banner, err := l.svcCtx.Banner.FindOneNoCache(l.ctx, tx, id)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var skipMedia bool
	if in.SkipMedia != nil && *in.SkipMedia > 0 {
		skipMedia = true
	}

	if in.PicUrl != nil {
		banner.PicURL = strings.TrimSpace(*in.PicUrl)
	}
	if in.Type != nil {
		banner.Type = uint8(*in.Type)
	}
	if in.Title != nil {
		banner.Title = strings.TrimSpace(*in.Title)
	}
	if in.LinkType != nil {
		banner.LinkType = uint8(*in.LinkType)
	}
	if in.LinkUrl != nil {
		banner.LinkURL = strings.TrimSpace(*in.LinkUrl)
	}
	if in.AdType != nil {
		banner.ObjectType = uint16(*in.AdType)
	}
	if in.AdId != nil {
		banner.ObjectID = *in.AdId
	}
	if in.Status != nil {
		banner.Status = uint8(*in.Status)
	}
	if in.Sort != nil {
		banner.Sort = uint16(*in.Sort)
	}
	banner.UpdatedAt = time.Now()
	if in.StartedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.StartedAt); err == nil {
			banner.StartedAt = null.TimeFrom(localTime)
		}
	}
	if in.EndedAt != nil {
		if localTime, err := modelx.ParseLocalTime(*in.EndedAt); err == nil {
			banner.EndedAt = null.TimeFrom(localTime.Add(time.Minute * -1))
		}
	}

	rel := &model.BannerRel{}
	if !skipMedia {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttachmentRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": []any{id},
		}
		filterMap[model.AttachmentRelationshipColumns.ObjectType] = map[string][]any{
			"equalTo": []any{globalkey.AttachmentLogTypeBanner},
		}
		list, _, err := l.svcCtx.Banner.GetMedia(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		mediaUidMap := make(map[uint64]*model.AttachmentRelationship)
		if len(list) > 0 {
			for _, v := range list {
				mediaUidMap[v.RelationshipID] = v
			}
		}

		if len(in.NewMedia) > 0 {
			var thumbnailOrder uint
			var thumbnailId uint64
			var thumbnailUrl string
			for idx, v := range in.NewMedia {
				var url string
				if v.Url != nil && len(*v.Url) > 0 { // v.Uri  content版本（包含?id）  v.Url  url当前版本 | attachment当前版本
					url = *v.Url
				}
				var uri string
				if v.Uri != nil && len(*v.Uri) > 0 {
					uri = *v.Uri
					if len(url) == 0 {
						url = uri
					}
				}
				if len(url) == 0 {
					continue
				}

				var thumbnail uint8
				if v.Thumbnail != nil && *v.Thumbnail > 0 {
					thumbnail = uint8(*v.Thumbnail)
				}
				var order uint
				if v.Order != nil {
					order = uint(*v.Order)
				} else {
					order = uint(idx) + globalkey.AttachmentOrderOffset
				}
				var altText string
				if v.AltText != nil && len(*v.AltText) > 0 {
					altText = *v.AltText
				}
				var meta []string
				if v.Name != nil && len(*v.Name) > 0 {
					meta = append(meta, "filename:"+*v.Name)
					if len(altText) == 0 {
						altText = *v.Name
					}
				}
				if v.MetaData != nil && len(*v.MetaData) > 0 {
					meta = append(meta, *v.MetaData)
				}
				if v.MimeType != nil && len(*v.MimeType) > 0 {
					meta = append(meta, "mimeType:"+*v.MimeType)
				}
				var metaData string = strings.Join(meta, ";")
				var mediaId uint64
				if v.Id != nil && len(*v.Id) > 0 {
					if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
						mediaId = uint64(i)
					}
				}
				var uid uint64
				if v.Uid != nil && *v.Uid > 0 {
					uid = *v.Uid
				}

				if uid > 0 { // 原有缩略图
					if media, ok := mediaUidMap[uid]; ok { // 存在，修改，否则无效
						delete(mediaUidMap, uid)
						rel.Media = append(rel.Media, &model.AttachmentRelationship{
							RelationshipID:      media.RelationshipID,
							AttachmentID:        mediaId,
							AttachmentThumbnail: thumbnail,
							AttachmentOrder:     order,
							AttachmentImageURL:  url,
							AttachmentImageAlt:  altText,
							AttachmentImageMeta: metaData,
						})
					}
					continue
				}

				rel.Media = append(rel.Media, &model.AttachmentRelationship{
					AttachmentID:        mediaId,
					AttachmentThumbnail: thumbnail,
					AttachmentOrder:     order,
					AttachmentImageURL:  url,
					AttachmentImageAlt:  altText,
					AttachmentImageMeta: metaData,
				})
			}

			for _, v := range rel.Media {
				if v.AttachmentThumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > v.AttachmentOrder) { // thumbnailOrder尚未赋值，或当前值更小
					thumbnailOrder = v.AttachmentOrder
					thumbnailId = v.AttachmentID
					thumbnailUrl = v.AttachmentImageURL
				}
			}

			if len(banner.PicURL) == 0 && thumbnailId > 0 && len(thumbnailUrl) > 0 {
				banner.PicID = thumbnailId
				banner.PicURL = thumbnailUrl
			}
		}

		for _, v := range mediaUidMap {
			rel.DelMediaIds = append(rel.DelMediaIds, v.RelationshipID)
		}
	}

	err = l.svcCtx.Banner.Update(l.ctx, tx, banner, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &backend.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
